<?php
require_once __DIR__ . '/../core/config.php';
require_once __DIR__ . '/../extend/phpmail/vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

function get_mail_server_info() {
    $pdo = connect_db();
    $stmt = $pdo->query("SELECT * FROM star_mail WHERE uid = 1");
    return $stmt->fetch(PDO::FETCH_ASSOC);
}
// 获取用户数量函数
function get_user_count() {
    $pdo = connect_db();
    try {
        $stmt = $pdo->query("SELECT COUNT(*) FROM star_user");
        $count = $stmt->fetchColumn();
        return json_response(200, '获取成功', ['count' => $count]);
    } catch (PDOException $e) {
        return json_response(500, '获取失败: ' . $e->getMessage());
    }
}

// 获取系统信息函数
function system_message() {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT app_name, app_domain, app_introduce, app_initiate, app_time FROM star_system WHERE uid = 1");
        $stmt->execute();
        $system_info = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$system_info) {
            return json_response(500, '系统信息未找到');
        }
        $app_time = strtotime($system_info['app_time']);
        $current_time = time();
        $time_diff = ($current_time - $app_time) / (60 * 60 * 24);
        $response_data = [
            'app_name' => $system_info['app_name'],
            'app_domain' => $system_info['app_domain'],
            'app_introduce' => $system_info['app_introduce'],
            'app_initiate' => $system_info['app_initiate'],
            'app_time' => floor($time_diff)
        ];
        return json_response(200, '获取成功', $response_data);
    } catch (PDOException $e) {
        return json_response(500, '获取失败: ' . $e->getMessage());
    }
}

// 修改系统信息函数
function modify_system($account, $app_name = null, $app_domain = null, $app_introduce = null, $app_initiate = null, $app_time = null) {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT user_permissions, user_token FROM star_user WHERE account = :account");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$user) {
            return json_response(500, '账号未注册');
        }
        if ($user['user_permissions'] == 1) {
            return json_response(500, '账号权限不足');
        }
        if ($user['user_permissions'] == 2) {
            return json_response(500, '账号已被封禁且权限不足!');
        }
        $current_time = time();
        $token_time = strtotime($user['user_token']);
        if ($token_time < $current_time) {
            return json_response(500, '账号未登录');
        }
        $update_fields = [];
        $params = [];
        if ($app_name !== null) {
            $update_fields[] = 'app_name = :app_name';
            $params['app_name'] = $app_name;
        }
        if ($app_domain !== null) {
            $update_fields[] = 'app_domain = :app_domain';
            $params['app_domain'] = $app_domain;
        }
        if ($app_introduce !== null) {
            $update_fields[] = 'app_introduce = :app_introduce';
            $params['app_introduce'] = $app_introduce;
        }
        if ($app_initiate !== null) {
            $update_fields[] = 'app_initiate = :app_initiate';
            $params['app_initiate'] = $app_initiate;
        }
        if ($app_time !== null && $app_time !== '') {
            $update_fields[] = 'app_time = :app_time';
            $params['app_time'] = $app_time;
        }
        if (empty($update_fields)) {
            return json_response(500, '未提供任何需要修改的字段');
        }
        $sql = "UPDATE star_system SET " . implode(', ', $update_fields) . " WHERE uid = 1";
        $stmt = $pdo->prepare($sql);
        foreach ($params as $key => $value) {
            $stmt->bindParam(':' . $key, $value, PDO::PARAM_STR);
        }
        $stmt->execute();
        return json_response(200, '系统信息修改成功');
    } catch (PDOException $e) {
        return json_response(500, '修改失败: ' . $e->getMessage());
    }
}

// 软件启动数量增加函数
function increment_app_initiate() {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT app_initiate FROM star_system WHERE uid = 1");
        $stmt->execute();
        $current_initiate = $stmt->fetchColumn();
        if ($current_initiate === false) {
            return json_response(500, '系统信息未找到');
        }
        $new_initiate = $current_initiate + 1;
        $stmt = $pdo->prepare("UPDATE star_system SET app_initiate = :app_initiate WHERE uid = 1");
        $stmt->bindParam(':app_initiate', $new_initiate, PDO::PARAM_INT);
        $stmt->execute();
    } catch (PDOException $e) {
        return json_response(500, '更新失败: ' . $e->getMessage());
    }
}

// 软件启动图
function startup_diagram() {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT app_startup_diagram FROM star_system WHERE uid = 1");
        $stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$result) {
            return json_response(500, '启动图未配置');
        }
        return json_response(200, $result['app_startup_diagram']);
    } catch (PDOException $e) {
        return json_response(500, '操作失败: ' . $e->getMessage());
    }
}

// 软件远程公告
function announcement() {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("
            SELECT app_announcement_title, app_announcement_body 
            FROM star_system 
            WHERE uid = 1
        ");
        $stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$result) {
            return json_response(500, '公告未配置');
        }
        return json_response(200, '', [
            'title' => $result['app_announcement_title'],
            'body' => $result['app_announcement_body']
        ]);
    } catch (PDOException $e) {
        return json_response(500, '操作失败: ' . $e->getMessage());
    }
}

// 远程公告修改
function change_announcement($title, $body) {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("
            UPDATE star_system 
            SET app_announcement_title = :title, app_announcement_body = :body 
            WHERE uid = 1
        ");
        $stmt->bindParam(':title', $title, PDO::PARAM_STR);
        $stmt->bindParam(':body', $body, PDO::PARAM_STR);
        $stmt->execute();

        return json_response(200, '公告更新成功');
    } catch (PDOException $e) {
        return json_response(500, '操作失败: ' . $e->getMessage());
    }
}


// 获取轮播图广告列表
function advertisement() {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("
            SELECT app_advertisement_title, app_advertisement_body, app_advertisement_url 
            FROM star_system 
            WHERE uid = 1
        ");
        $stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$result) {
            return json_response(500, '广告未配置');
        }
        $titles = explode('-', $result['app_advertisement_title']);
        $bodies = explode('-', $result['app_advertisement_body']);
        $urls = explode('-', $result['app_advertisement_url']);
        $data = [];
        foreach ($titles as $index => $title) {
            $data['title' . ($index + 1)] = trim($title);
            $data['body' . ($index + 1)] = trim($bodies[$index]);
            $data['url' . ($index + 1)] = trim($urls[$index]);
        }
        return json_response(200, '', $data);
    } catch (PDOException $e) {
        return json_response(500, '操作失败: ' . $e->getMessage());
    }
}

// 修改轮播图广告
function change_advertisement($title, $body, $url) {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("
            UPDATE star_system 
            SET app_advertisement_title = :title, 
                app_advertisement_body = :body, 
                app_advertisement_url = :url 
            WHERE uid = 1
        ");
        $stmt->bindParam(':title', $title, PDO::PARAM_STR);
        $stmt->bindParam(':body', $body, PDO::PARAM_STR);
        $stmt->bindParam(':url', $url, PDO::PARAM_STR);
        $stmt->execute();
        return json_response(200, '广告更新成功');
    } catch (PDOException $e) {
        return json_response(500, '操作失败: ' . $e->getMessage());
    }
}

// 添加远程通知
function notification($title, $body, $account) {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT user_permissions, user_token FROM star_user WHERE account = :account");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$user) {
            return json_response(500, '账号未注册');
        }
        if ($user['user_permissions'] == 1) {
            return json_response(500, '账号权限不足');
        }
        if ($user['user_permissions'] == 2) {
            return json_response(500, '账号已被封禁且权限不足!');
        }
        $current_time = time();
        $token_time = strtotime($user['user_token']);
        if ($token_time < $current_time) {
            return json_response(500, '账号未登录');
        }
        $current_time = date('Y-m-d H:i:s');
        $stmt = $pdo->prepare("
            INSERT INTO star_notification (title, body, time)
            VALUES (:title, :body, :time)
        ");
        $stmt->bindParam(':title', $title, PDO::PARAM_STR);
        $stmt->bindParam(':body', $body, PDO::PARAM_STR);
        $stmt->bindParam(':time', $current_time, PDO::PARAM_STR);
        $stmt->execute();
        $stmt = $pdo->query("SELECT mail FROM star_user");
        $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $mail_info = get_mail_server_info();
        if (!$mail_info) {
            return json_response(500, '邮件服务器信息未配置');
        }
        $stmt = $pdo->query("SELECT app_name FROM star_system WHERE uid = 1");
        $app_name = $stmt->fetch(PDO::FETCH_ASSOC)['app_name'] ?? '';
        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host = $mail_info['host'];
            $mail->SMTPAuth = true;
            $mail->Username = $mail_info['username'];
            $mail->Password = $mail_info['password'];
            $mail->SMTPSecure = $mail_info['agreement'];
            $mail->Port = $mail_info['port'];
            $mail->setFrom($mail_info['mail_address'], $mail_info['mail_user']);
            $mail->isHTML(true);
            $mail->Subject = $title;
            $mail->Body = "<!DOCTYPE html>
<html lang='zh-CN'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <style>
        body {
            font-family: 'Comic Sans MS', cursive, sans-serif;
            background-color: #F0F0F0;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 600px;
            margin: 0 auto;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .header {
            background-image: url('https://api.lovestory.wiki/api/mc/?username=2036513862');    
            background-size: cover;
            height: 300px;
            border-top-left-radius: 10px;
            border-top-right-radius: 10px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .header h1 {
            color: white;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
            font-size: 36px;
            margin: 0;
        }
        .content {
            padding: 20px;
        }
        .content p {
            font-size: 18px;
            line-height: 1.6;
        }
        .footer {
            background-color: #333;
            color: white;
            text-align: center;
            padding: 10px;
            border-bottom-left-radius: 10px;
            border-bottom-right-radius: 10px;
            font-size: 14px;
        }
        .button {
            display: inline-block;
            background-color: #FF6600;
            color: white;
            padding: 10px 20px;
            text-decoration: none;
            border-radius: 5px;
            font-weight: bold;
            margin-top: 15px;
        }
        .button:hover {
            background-color: #FF8800;
        }
        .highlight {
            color: red;
        }
    </style>
</head>
<body>
    <div class='container'>
        <div class='header'>
            <h1>{$app_name}-通知</h1>
        </div>
        <div class='content'>
            <h1>亲爱的小伙伴：</h1>
            <p>这里有一个重要通知需要您查看一下</p>
            <h2>通知内容:<span class='highlight'>{$body}</span></h2>
        </div>
        <div class='footer'>
            &copy; 2025 繁控星理-<a href='https://lovestory.wiki/index.php/archives/564/'>了解更多</a>
        </div>
    </div>
</body>
</html>";
            foreach ($users as $user) {
                $mail->addAddress($user['mail']);
            }

            $mail->send();
            return json_response(200, '通知记录成功');
        } catch (Exception $e) {
            return json_response(500, '邮件发送失败: ' . $e->getMessage());
        }
    } catch (PDOException $e) {
        return json_response(500, '操作失败: ' . $e->getMessage());
    }
}

//删除远程通知
function delete_notification($uid) {
    $pdo = connect_db();
    try {
        $checkStmt = $pdo->prepare("SELECT 1 FROM star_notification WHERE uid = :uid");
        $checkStmt->bindParam(':uid', $uid, PDO::PARAM_INT);
        $checkStmt->execute();
        if ($checkStmt->fetch(PDO::FETCH_ASSOC) === false) {
            return json_response(404, '该通知不存在或者已删除');
        }
        $stmt = $pdo->prepare("DELETE FROM star_notification WHERE uid = :uid");
        $stmt->bindParam(':uid', $uid, PDO::PARAM_INT);
        $stmt->execute();
        return json_response(200, '通知删除成功');
    } catch (PDOException $e) {
        return json_response(500, '操作失败: ' . $e->getMessage());
    }
}

// 获取通知列表
function notification_list() {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT * FROM star_notification");
        $stmt->execute();
        $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
        if (empty($notifications)) {
            return json_response(500, '没有通知记录');
        }
        return json_response(200, '', $notifications);
    } catch (PDOException $e) {
        return json_response(500, '操作失败: ' . $e->getMessage());
    }
}

// 根据时间返回不同的音频文件
function time_mp3() {
    $pdo = connect_db();
    try {
        $current_hour = date('H');
        if ($current_hour >= 5 && $current_hour < 12) {
            $audio_file = '早上好.mp3';
        } elseif ($current_hour >= 12 && $current_hour < 18) {
            $audio_file = '下午好.mp3';
        } else {
            $audio_file = '晚上好.mp3';
        }
        $file_path = __DIR__ . '/../assets/mp3/' . $audio_file;
        if (!file_exists($file_path)) {
            return json_response(500, '音频文件不存在');
        }
        header('Content-Type: audio/mpeg');
        readfile($file_path);
    } catch (PDOException $e) {
        return json_response(500, '操作失败: ' . $e->getMessage());
    }
}